<template>
  <div class="main-box">
    <DeptTree
      label="deptName"
      title="部门列表"
      :request-api="getUserDeptTree"
      :default-value="initParam.deptId"
      @change="changeDeptTree"
      ref="deptTreeRef"
    />
    <div class="table-box">
      <ProTable
        ref="proTableRef"
        title="用户列表"
        :indent="20"
        :columns="columns"
        :search-columns="searchColumns"
        :request-api="getTableList"
        :search-col="4"
        :init-param="initParam"
        :border="false"
        :loading-time="200"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button
            v-auth="'system:user:add'"
            type="primary"
            :icon="CirclePlus"
            @click="openUserAdd('新增用户')"
          >
            新增用户
          </el-button>
          <el-button
            v-auth="'system:user:remove'"
            type="danger"
            :icon="Delete"
            plain
            :disabled="!scope.isSelected"
            @click="batchDelete(scope.selectedListIds)"
          >
            批量删除
          </el-button>
          <el-button
            type="info"
            :icon="OfficeBuilding"
            plain
            :disabled="!scope.isSelected"
            @click="settingDept(scope)"
          >
            <!-- <el-icon class="el-icon--left">
              <SvgIcon name="org" />
            </el-icon> &nbsp;&nbsp;  -->
            设置部门
          </el-button>
          <el-button
            type="info"
            :icon="OfficeBuilding"
            plain
            :disabled="!scope.isSelected"
            @click="settingPost(scope)"
          >
            设置岗位
          </el-button>
          <el-button
            type="info"
            :icon="Unlock"
            plain
            :disabled="!scope.isSelected"
            @click="unlock(scope.selectedListIds)"
          >
            解锁
          </el-button>
        </template>

        <template #username="{ row }">
          <el-button type="primary" link>
            {{ row?.username }}
          </el-button>
        </template>

        <template #logo="{ row }">
          <el-image v-if="row.logo" :src="row.logo"></el-image>
          <div v-else>--</div>
        </template>

        <template #deptInfo="{ row }">
          <el-tag class="user-item">
            {{ row.dept.deptName }}
          </el-tag>
        </template>

        <template #roleInfo="{ row }">
          <el-tag class="user-item" v-for="tag in row.roleList" :key="tag.id" type="success">
            {{ tag.roleName }}
          </el-tag>
        </template>

        <template #postInfo="{ row }">
          <el-tag class="user-item" v-for="tag in row.postList" :key="tag.id" type="info">
            {{ tag.postName }}
          </el-tag>
        </template>

        <template #operation="{ row }">
          <div class="btn-group">
            <el-button
              v-auth="'system:user:update'"
              type="primary"
              link
              :icon="EditPen"
              @click="openUserEdit('编辑用户', row)"
            >
              编辑
            </el-button>
            <el-button
              v-auth="'system:user:setRole'"
              type="primary"
              :icon="User"
              link
              @click="openUserPermissions('设置角色', row)"
            >
              设置角色
            </el-button>
            <div
              class="el-dropdown"
              v-auth="[
                {
                  type: 'or',
                  conditions: ['system:user:unlock', 'system:user:resetPwd', 'system:user:remove']
                }
              ]"
            >
              <el-dropdown trigger="click">
                <el-button type="primary" link :icon="DArrowRight">更多</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <div v-auth="'system:user:unlock'">
                      <el-dropdown-item :icon="Unlock" @click="unlock(row.id)">
                        解锁用户
                      </el-dropdown-item>
                    </div>

                    <div v-auth="'system:user:resetPwd'">
                      <el-dropdown-item type="primary" :icon="Refresh" link @click="resetPwd(row)">
                        重置密码
                      </el-dropdown-item>
                    </div>
                    <div v-auth="'system:user:update'">
                      <el-dropdown-item :icon="OfficeBuilding" @click="settingDept(row)">
                        设置部门
                      </el-dropdown-item>
                    </div>

                    <div v-auth="'system:user:update'">
                      <el-dropdown-item :icon="HomeFilled" @click="settingPost(row)">
                        设置岗位
                      </el-dropdown-item>
                    </div>

                    <div v-auth="'system:user:remove'">
                      <el-dropdown-item v-if="row.id !== 1" :icon="Delete" @click="deleteInfo(row)">
                        <!-- <tag style="color: red"></tag> -->
                        删除
                      </el-dropdown-item>
                    </div>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </template>
      </ProTable>
      <UserAdd ref="userAddRef" />
      <UserEdit ref="userEditRef" />
      <UserPermissions ref="userPermissionsRef" />
      <UserDeptForm ref="userDeptFormRef" @submit="refreshDeptTree" />
      <UserPostForm ref="userPostFormRef" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  CirclePlus,
  Delete,
  EditPen,
  User,
  Unlock,
  Refresh,
  DArrowRight,
  School,
  OfficeBuilding,
  HomeFilled
} from '@element-plus/icons-vue'
import ProTable from '@/components/ProTable/index.vue'
import DeptTree from '@/views/system/accountManage/components/DeptTree.vue'
import { useHandleData } from '@/hooks/useHandleData'
import {
  addUser,
  deleteUser,
  editUser,
  getUserDeptTree,
  getUserList,
  setUserRole,
  unlockUser,
  resetPassword,
  getUserDetailApi
} from '@/api/modules/system/user'
import { useOptionsStore } from '@/stores/modules/options'
import UserAdd from '@/views/system/accountManage/components/UserAdd.vue'
import UserEdit from '@/views/system/accountManage/components/UserEdit.vue'
import UserPermissions from '@/views/system/accountManage/components/UserPermissions.vue'
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface'
import type { IUser } from '@/api/interface/system/user'
import type { IRole } from '@/api/interface/system/role'
import { reactive, ref } from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import UserDeptForm from '@/views/system/accountManage/components/UserDeptForm.vue'
import UserPostForm from '@/views/system/accountManage/components/UserPostForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
defineOptions({
  name: 'accountManage'
})

const optionsStore = useOptionsStore()
// const accountStatusOption = [
//   { id: '10000001', codeName: '正常', callbackShowStyle: 'success' },
//   { id: '10000002', codeName: '禁用', callbackShowStyle: 'info' },
//   { id: '10000003', codeName: '禁言', callbackShowStyle: 'info' }
// ]
const accountStatusOption = optionsStore.getDictOptions('account_status')

// 表格配置项  prop: 可以自定义 template  也可以自动渲染对应返回值内容
const columns: ColumnProps<IUser.Info>[] = [
  { type: 'selection', width: 55, selectable: (row) => row.id !== 1 },
  { prop: 'username', label: '账户', width: 110, align: 'left' },
  { prop: 'nickName', label: '昵称', width: 110, align: 'left' },
  { prop: 'deptInfo', label: '部门', width: 100 },
  { prop: 'roleInfo', label: '角色', width: 150 },
  { prop: 'postInfo', label: '岗位', width: 150 },
  {
    prop: 'accountStatusCd',
    label: '状态',
    tag: true,
    enum: accountStatusOption,
    width: 80,
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  },
  { prop: 'mobile', label: '手机号', width: 120 },
  { prop: 'createTime', label: '创建时间', width: 125 },
  { prop: 'operation', label: '操作', width: 230, fixed: 'right' }
]

const searchColumns: SearchProps[] = [
  { prop: 'username', label: '账户', el: 'input' },
  { prop: 'mobile', label: '手机号', el: 'input' },
  {
    prop: 'isThisDeep',
    label: '直属部门',
    el: 'checkbox',
    defaultValue: true,
    tooltip: '直属部门只展示当前节点直接下级用户，不包含其后代'
  }
]

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref<ProTableInstance>()

// 获取table列表
const getTableList = (params: IUser.Query) => {
  return getUserList(params)
}

const userAddRef = ref<InstanceType<typeof UserAdd>>()
const openUserAdd = (title: string) => {
  const params: View.DefaultParams = {
    title,
    row: { age: 0 },
    api: addUser,
    getTableList: proTableRef.value?.getTableList
  }
  userAddRef.value?.acceptParams(params)
}

const userEditRef = ref<InstanceType<typeof UserEdit>>()
const openUserEdit = async (title: string, row: any = {}) => {
  const { data } = await getUserDetailApi({ id: row.id })
  const params: View.DefaultParams = {
    title,
    row: { ...data },
    api: editUser,
    getTableList: proTableRef.value?.getTableList
  }
  userEditRef.value?.acceptParams(params)
}

const userPermissionsRef = ref<InstanceType<typeof UserPermissions>>()
const openUserPermissions = (title: string, row = {}) => {
  const params = {
    title,
    row: row,
    api: setUserRole,
    getTableList: proTableRef.value?.getTableList
  }
  userPermissionsRef.value?.acceptParams(params)
  proTableRef.value?.getTableList()
}
const deptTreeRef = ref<InstanceType<typeof DeptTree>>()

// 删除信息
const deleteInfo = async (params: IUser.Info) => {
  await useHandleData(deleteUser, { ids: [params.id] }, `删除【${params.username}】用户`)
  proTableRef.value?.getTableList()
  refreshDeptTree()
}

// 批量删除信息
const batchDelete = async (ids: string[]) => {
  await useHandleData(deleteUser, { ids }, '删除所选用户信息')
  proTableRef.value?.clearSelection()
  proTableRef.value?.getTableList()
  refreshDeptTree()
}
const userDeptFormRef = ref<InstanceType<typeof UserDeptForm>>()
const userPostFormRef = ref<InstanceType<typeof UserPostForm>>()
const settingDept = (record: any) => {
  if (record.selectedListIds) {
    const params = {
      title: '批量设置部门',
      row: {},
      api: undefined,
      getTableList: proTableRef.value?.getTableList,
      selectedList: record.selectedList, //选中的行信息
      deptId: selectTreeId.value,
      selectIds: record.selectedListIds,
      isBatch: true
    }
    userDeptFormRef.value?.acceptParams(params)
  } else {
    console.log(record)
    const params = {
      title: '设置部门',
      row: {},
      api: undefined,
      getTableList: proTableRef.value?.getTableList,
      selectedList: [record], //选中的行信息
      deptId: record.deptId,
      selectIds: [record.id],
      isBatch: false
    }
    userDeptFormRef.value?.acceptParams(params)
  }
}

const settingPost = (record: any) => {
  if (record.selectedListIds) {
    const params = {
      title: '批量设置岗位',
      row: {},
      api: undefined,
      getTableList: proTableRef.value?.getTableList,
      selectedList: record.selectedList, //选中的行信息
      selectIds: record.selectedListIds,
      isBatch: true
    }
    userPostFormRef.value?.acceptParams(params)
  } else {
    console.log('设置岗位传入内容', record)
    const params = {
      title: '设置岗位',
      row: {},
      api: undefined,
      getTableList: proTableRef.value?.getTableList,
      selectedList: [record], //选中的行信息
      postIds: record.postList.map((post: { id: number }) => post.id),
      selectIds: [record.id],
      isBatch: false
    }
    console.log(params)

    userPostFormRef.value?.acceptParams(params)
  }
}

const unlock = async (id: string | string[]) => {
  if (Array.isArray(id)) {
    await unlockUser({ ids: id })
  } else {
    await unlockUser({ ids: [id] })
  }
  ElMessage.success(`解锁成功！`)
}

const resetPwd = async (row: any) => {
  const param = { id: row?.id }
  ElMessageBox.confirm('您确认要重置账户 [' + row.username + '] 密码?', '温馨提示', {
    type: 'warning'
  }).then(async () => {
    await resetPassword(param)
    proTableRef.value?.getTableList()
    ElMessage.success({
      message: `账户 [` + row.username + `] 重置密码成功！`,
      duration: 5000,
      showClose: true
    })
  })
}

const initParam = reactive({ deptId: -1 })

//全部，后端设置treeId=-1,  未设置部门, 后端设置treeId=-2
const selectTreeId = ref<number>()
const changeDeptTree = (val: number) => {
  if (val) {
    selectTreeId.value = val
    initParam.deptId = val
    proTableRef.value?.getTableList()
    proTableRef.value?.clearSelection()
  }
}

const refreshDeptTree = () => {
  deptTreeRef.value?.refresh()
}
</script>

<style scoped lang="scss">
.user-item {
  margin: 5px;
}

.btn-group {
  display: flex;
  justify-content: center;
}

.el-button + .el-button + .el-dropdown {
  margin-left: 12px;
}
</style>
